package cn.zjj._04_tran;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 消费者
 */
public class Consumer {
    public static void main(String[] args) throws Exception{
        //1.创建消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("tran_consumer_group");


        //2.连接mq,设置nameserver
        consumer.setNamesrvAddr("localhost:9876");
        //3.订阅主题
        consumer.subscribe("tran","hellojava");
        //4.注册消息监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt messageExt : list) {
                    //获取数据体,即我们传的,并转为字符串utf8格式
                    String result = new String(messageExt.getBody(), StandardCharsets.UTF_8);
                    System.out.println(result);
                }
                //返回成功提示
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5.启动消费者
        consumer.start();
    }
}
